package com.app.service.impl;

import com.alibaba.excel.EasyExcel;
import com.app.controller.importExcel.ImportExcelListener;
import com.app.mapper.MilitaryNewSportsMapper;
import com.app.model.DepartmentModel;
import com.app.model.MilitarySportsNewModel;
import com.app.service.DepartmentService;
import com.app.service.MilitaryNewSportsService;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TestFileUtil;
import com.app.vo.MilitaryNewSportsVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.ListUtils;
import org.thymeleaf.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
public class MilitaryNewSportsServiceImpl implements MilitaryNewSportsService {
    @Autowired
    private MilitaryNewSportsMapper militarySportsMapper;

    @Autowired
    private DepartmentService departmentService;

    @Override
    public void update(MilitarySportsNewModel militarySportsModel) {
        militarySportsMapper.updateById(militarySportsModel);
    }

    @Override
    public void insert(MilitarySportsNewModel militarySportsModel) {
        militarySportsMapper.insert(militarySportsModel);
    }

    @Override
    public MilitaryNewSportsVo getMilitarySportsList(Integer page, Integer limit, String name, Integer departmentId, Integer sortType) {
        Page<MilitarySportsNewModel> page1 = new Page<>();
        page1.setCurrent(page);
        page1.setSize(limit);
        QueryWrapper<MilitarySportsNewModel> queryWrapper = new QueryWrapper<>();
        if (name != null && !name.equals("")) {
            queryWrapper.eq("name", name);
        } else {
            queryWrapper.select();
        }
        if (departmentId != null) {
            queryWrapper.eq("department_id", departmentId);
        }
        if (sortType==null || sortType==1){
            queryWrapper.orderByAsc("number");
        }else {
            queryWrapper.orderByDesc("number");
        }

        Page<MilitarySportsNewModel> militarySportsModelPage = militarySportsMapper.selectPage(page1, queryWrapper);
        for (int i = 0; i < militarySportsModelPage.getRecords().size(); i++) {
            if (militarySportsModelPage.getRecords().get(i).getGender() != null && militarySportsModelPage.getRecords().get(i).getGender() == 1) {
                militarySportsModelPage.getRecords().get(i).setGenderText("男");
            } else if (militarySportsModelPage.getRecords().get(i).getGender() != null) {
                militarySportsModelPage.getRecords().get(i).setGenderText("女");
            }
        }
        MilitaryNewSportsVo vo = new MilitaryNewSportsVo();
        vo.setList(militarySportsModelPage.getRecords());
        vo.setCount((int) militarySportsModelPage.getTotal());
        return vo;
    }

    @Override
    public void deleteMilitarySportsList(Integer id) {
        militarySportsMapper.deleteById(id);
    }

    @Override
    public MilitarySportsNewModel selectMilitarySportsById(Integer id) {
        return militarySportsMapper.selectById(id);
    }

    @Override
    public List<MilitarySportsNewModel> getPlantByIds(List<Integer> appIdList) {
        QueryWrapper<MilitarySportsNewModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select().in("id", appIdList);
        return militarySportsMapper.selectList(queryWrapper);
    }

    //导入军事体育信息
    @Override
    public String importMilitarySports(MultipartFile file) throws IOException {
        List<String> errorList = new ArrayList<>();
        String path = TestFileUtil.getPath() + "excel.xlsx";
        File localFile = new File(path);
        file.transferTo(localFile);
        String filePath = localFile.getAbsolutePath();
        AtomicReference<Integer> row = new AtomicReference<>(0);
        try {
            EasyExcel.read(filePath, MilitarySportsNewModel.class, new ImportExcelListener<MilitarySportsNewModel>(dateList -> {
                for (MilitarySportsNewModel militarySportsModel : dateList) {
                    DepartmentModel departmentModel = departmentService.getdepByName(militarySportsModel.getDepartmentName());
                    if (departmentModel != null) {
                        militarySportsModel.setDepartmentId(departmentModel.getId());
                    }
                    if (militarySportsModel.getGenderText().equals("男")) {
                        militarySportsModel.setGender(1);
                    } else {
                        militarySportsModel.setGender(2);
                    }
                    militarySportsModel.setCreateTime(CommonHelp.getNowTimestamp());
                    militarySportsMapper.insert(militarySportsModel);
                    row.set(row.get() + 1);
                }
            }, errorList)).sheet().headRowNumber(2).doRead();
        } catch (Exception e) {
            e.printStackTrace();
            return "Excel导入失败";
        }
        localFile.delete();
        if (row.get() == 0) {
            return "导入0条，请检查模版或者数据格式";
        }
        StringBuilder msg = new StringBuilder("成功导入" + row + "行。");
        if (errorList.size() != 0) {
            for (String error : errorList) {
                msg.append(error);
            }
        }
        return msg.toString();
    }

    /**
     * 军事体育的批量删除
     * @param ids
     * @return
     */
    @Override
    public Result<Object> deleteBatchByIds(String ids) {
        // 参数校验
        if (StringUtils.isEmpty(ids)) {
            return Result.success("参数为空，无需删除");
        }
        List<Integer> idsList = Arrays.stream(ids.split(","))
                .map(Integer::valueOf)
                .collect(Collectors.toList());
        // 批量删除
        if (!ListUtils.isEmpty(idsList)) {
            militarySportsMapper.deleteBatchIds(idsList);
            return Result.success("批量删除成功");
        } else {
            return Result.success("批量删除失败，数据为空");
        }
    }
}
